package com.example.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.entity.Order;
import com.example.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;
import com.alipay.api.AlipaySignature;

import java.util.List;
import java.util.Map;

@Service
public class AlipayService {
    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderRepository orderRepository;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Transactional
    public String createPayment(List<Map<String, Object>> items, String totalAmount) throws Exception {
        // 创建订单
        Order order = new Order();
        order.setTotalAmount(totalAmount);
        order.setStatus("PENDING");
        order = orderRepository.save(order);

        // 创建支付宝请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        // 构建请求参数
        String bizContent = String.format(
            "{\"out_trade_no\":\"%s\"," +
            "\"total_amount\":\"%s\"," +
            "\"subject\":\"商城订单\"," +
            "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}",
            order.getOrderId(),
            totalAmount
        );
        request.setBizContent(bizContent);

        // 调用支付宝接口
        return alipayClient.pageExecute(request).getBody();
    }

    @Transactional
    public void handlePaymentNotify(Map<String, String> params) {
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, publicKey, "UTF-8", "RSA2");
        if (!signVerified) {
            throw new RuntimeException("支付宝回调签名验证失败");
        }

        // 获取订单号
        String orderId = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");

        // 更新订单状态
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            Order order = orderRepository.findByOrderId(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            order.setStatus("PAID");
            orderRepository.save(order);
        }
    }
} 